<template>
  <div class="sellingRecord">
    <div class="title fl">
      委托记录
    </div>
    <el-button class="fr" type="primary" @click="$router.push({name: 'SellingHouse'})">我要卖房</el-button>
    <!-- 表格 -->
    <el-table :data="initData.list" style="width: 100%">
      <el-table-column align="center" header-align="center" label="小区名称" width="150">
        <template slot-scope="scope">
          {{scope.row['estate.estateName']}}
        </template>
      </el-table-column>
      <el-table-column align="center" header-align="center" prop="houseNum" label="栋阁房号">
      </el-table-column>
      <!-- <el-table-column align="center" header-align="center" prop="kind" label="户型">
      </el-table-column> -->
      <el-table-column align="center" header-align="center" prop="price" label="期望价格">
        <template slot-scope="scope">
          {{scope.row.sup}}万
        </template>
      </el-table-column>
      <el-table-column align="center" header-align="center" prop="state" label="状态">
        <template slot-scope="scope">
          {{((key)=>{
            switch(key){
              case 0: return '审核中';break;
              case 1: return '挂牌中';break;
              case 2: return '已出售';break;
              case 3: return '取消委托';break;
              case 4: return '审核失败';break;
              case -1: return '下架整改中';break;
            }
          })(scope.row.state)}}
        </template>
      </el-table-column>
      <el-table-column align="center" header-align="center" prop="createdAt" label="委托日期" width="160">
        <template slot-scope="scope">
          {{$util.formDate(scope.row.createdAt)}}
        </template>
      </el-table-column>
      <el-table-column align="center" header-align="center" label="操作" width="250">
        <template slot-scope="scope">
          <div class="btns">
            <el-button size="small" plain type="primary" @click="openCheck(scope.row)">查看</el-button>

            <el-button size="small" type="success" slot="reference" v-show="scope.row.state == 3" @click="openEdit(scope.row)">委托</el-button>

            <el-button size="small" v-show="scope.row.state == 4" type="warning" @click="openEdit(scope.row)">编辑</el-button>
            <!-- <el-button size="small" v-show="scope.row.state != 3 && scope.row.state != 2" type="danger" @click="cancelSell(scope.row)">取消委托</el-button> -->

            <el-popconfirm title="确定取消委托吗？" v-show="scope.row.state != 3 && scope.row.state != 2" @confirm="cancelSell(scope.row)">
              <el-button size="small" type="danger" slot="reference">取消委托</el-button>
            </el-popconfirm>

            <el-popconfirm title="确定删除此记录吗？" v-show="scope.row.state == 2 || scope.row.state == 3" @confirm="delRecord(scope.row)">
              <el-button size="small" type="primary" slot="reference">删除记录</el-button>
            </el-popconfirm>
          </div>
        </template>
      </el-table-column>

    </el-table>
    <!-- 分页 -->
    <el-pagination @current-change="handleCurrentChange" :current-page="params.page" :page-size="10" layout="total, prev, pager, next" :total="params.total">
    </el-pagination>

    <!-- 委托/编辑对话框 -->
    <el-dialog :visible.sync="dialog.edit" width="500px" center>
      <template slot="title">
        <b>编辑信息</b>
      </template>
      <el-form ref="editData" :model="editData" label-width="80px" :rules="rules">
        <el-form-item label="小区名称" prop="estate">
          <el-autocomplete class="inline-input" v-model="editData.estate" :fetch-suggestions="querySearch" placeholder="请输入小区名或楼盘" :trigger-on-focus="false" @select="handleSelect" @change="editData.estateId = ''"></el-autocomplete>
        </el-form-item>

        <el-form-item label="栋阁房号" prop="houseNumber">
          <el-input class="houseNumber" v-model="editData.dgName" placeholder="楼栋号" autocomplete="off"></el-input>
          <el-input class="houseNumber" v-model="editData.number" placeholder="门牌号" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="户型" prop="houseKind">
          <el-select class="kind" v-model="editData.kind1" placeholder="室">
            <el-option v-for="item in options.kind1" :key="item" :label="item" :value="item"></el-option>
          </el-select>
          <el-select class="kind" v-model="editData.kind2" placeholder="厅">
            <el-option v-for="item in options.kind2" :key="item" :label="item" :value="item"></el-option>
          </el-select>
          <el-select class="kind" v-model="editData.kind3" placeholder="卫">
            <el-option v-for="item in options.kind3" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item class="price" label="期望价格" prop="sup">
          <el-input v-model="editData.sup" placeholder="您期望售出的价格" autocomplete="off" onkeyup="this.value=this.value.replace(/\D\./g,'')">
            <template slot='suffix'>
              <span class="unit">万元</span>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item class="area" label="建筑面积" prop="builtArea">
          <el-input v-model="editData.builtArea" placeholder="您房屋的建筑面积" autocomplete="off" onkeyup="this.value=this.value.replace(/\D\./g,'')">
            <template slot='suffix'>
              <span class="unit">㎡</span>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item class="user-name" label="姓名" prop="userName">
          <el-input v-model="editData.userName" placeholder="怎么称呼您" autocomplete="off"></el-input>
          <div class="sex fr">
            <a href="javascript:;" :class="editData.sex == 1 ? 'active' : ''" @click="changeSex(1)">先生</a>
            <a href="javascript:;" :class="editData.sex == 0 ? 'active' : ''" @click="changeSex(0)">女士</a>
          </div>
        </el-form-item>

        <el-form-item>
          <el-button @click="dialog.edit = false">取消</el-button>
          <el-button type="primary" @click="selling">提交委托</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 查看对话框 -->
    <el-dialog :visible.sync="dialog.check" width="300px" center>
      <template slot="title">
        <b>查看信息</b>
      </template>
      <el-form ref="editData" :model="editData" label-width="125px">
        <el-form-item label="小区名称：" style="margin-bottom: 0px;">
          {{editData.estate}}
        </el-form-item>

        <el-form-item label="栋阁房号：" style="margin-bottom: 0px;">
          {{editData.houseNumber}}
        </el-form-item>

        <el-form-item label="户型：" style="margin-bottom: 0px;">
          {{editData.houseKind}}
        </el-form-item>

        <el-form-item label="期望价格：" style="margin-bottom: 0px;">
          {{editData.sup}}万元
        </el-form-item>

        <el-form-item label="建筑面积：" style="margin-bottom: 0px;">
          {{editData.builtArea}}㎡
        </el-form-item>

        <el-form-item label="单价：" style="margin-bottom: 0px;">
          {{editData.sub}}元/㎡
        </el-form-item>

        <div style="text-align: center;">
          <el-button type="primary" @click="dialog.check = false" style="width: 100px">确定</el-button>
        </div>
      </el-form>
    </el-dialog>

  </div>
</template>

<script>
export default {
  name: "sellingRecord",
  data() {
    return {
      initData: {
        list: [
          // {
          //   id: 1,
          //   estate: "金碧花园三期",
          //   houseNumber: "2栋301房",
          //   kind: "2室1厅1卫",
          //   price: "200",
          //   state: 0,// -1-下架 0审核中 1在售 2-已售 3取消委托 4审核失败
          //   date: "2021-02-01",
          // },
          // {
          //   id: 2,
          //   estate: "金碧花园三期",
          //   houseNumber: "2栋301房",
          //   kind: "2室1厅1卫",
          //   price: "200",
          //   state: 1,// -1-下架 0审核中 1在售 2-已售 3取消委托 4审核失败
          //   date: "2021-02-01",
          // },
        ],
      },
      params: {
        page: 1,
        total: 0,
      },
      dialog: {
        edit: false,
        check: false
      },
      estateList: [],
      editData: {
        estate: "", // 小区
        estateId: '',// 小区id
        dgName: "", // 楼栋号
        number: "", // 门牌号
        houseNumber: "", // 栋阁房号dgName+number
        houseKind: "", // 户型
        kind1: '',
        kind2: '',
        kind3: '',
        sup: "", // 卖出价格
        builtArea: "", // 建筑面积
        userName: "", // 用户姓名
        sex: 1, // 用户性别  0=>女士/1=>先生
        userPhone: "", // 手机号
      },
      options: {
        // 户型-室
        kind1: ["1室", "2室", "3室", "4室", "5室", "6室", "7室", "8室", "9室"],
        // 户型-厅
        kind2: ["1厅", "2厅", "3厅", "4厅", "5厅", "6厅", "7厅", "8厅", "9厅"],
        // 户型-卫
        kind3: ["1卫", "2卫", "3卫", "4卫", "5卫", "6卫", "7卫", "8卫", "9卫"],
        // 房源类型
        // type: ["住宅", "公寓", "别墅"],
      },
      rules: {
        estate: [{ validator: this.validEstate, trigger: "blur" }],
        sup: [{ validator: this.validSup, trigger: "blur" }],
        builtArea: [{ validator: this.validBuiltArea, trigger: "blur" }],
        city: [{ validator: this.validCity, trigger: "change" }],
        areaPlace: [{ validator: this.validAreaPlace, trigger: "change" }],
        floor: [{ validator: this.validFloor, trigger: "change" }],
        floor2: [{ validator: this.validFloor2, trigger: "blur" }],
        userName: [{ validator: this.validUsername, trigger: "blur" }],
        userPhone: [{ validator: this.validPhone, trigger: "blur" }],
      },
    }
  },
  created() {
    this.init();
  },
  methods: {
    init() {
      this.axios({
        method: 'get',
        url: this.baseUrl + '/getSellingRecord',
        params: {
          userId: this.$cookies.get("__ui"),
          page: this.params.page,
        }
      }).then(res => {
        console.log('res==>', res)
        if (res.data.code == 200) {
          this.initData.list = res.data.data;
          this.params.total = res.data.total;
        }
      }).catch(err => {
        console.log('err==>', err)
        this.$message.error(res.data.msg)
      })
    },
    // 切换性别
    changeSex(s) {
      if (this.editData.sex == s) {
        return;
      }
      this.editData.sex = s;
    },
    // 打开查看
    openCheck(o) {
      this.editData = {
        estate: o['estate.estateName'], // 小区
        houseNumber: o.houseNum, // 栋阁房号dgName+number
        houseKind: o.kind, // 户型
        sup: o.sup, // 卖出价格
        builtArea: o.builtArea, // 建筑面积
        sub: o.sub, // 建筑面积
      };
      this.dialog.check = true;
    },
    // 小区输入框的输入建议
    querySearch(queryString, cb) {
      var estateList = this.estateList;
      var results = queryString ? estateList.filter(this.createFilter(queryString)) : estateList;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (estate) => {
        return (estate.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    // 获取所有小区名,地址和id
    loadAll() {
      this.axios({
        method: 'get',
        url: this.baseUrl + '/getEstate',
      }).then(res => {
        console.log('res==>', res)
        if (res.data.code == 200) {
          // let arr = [];
          res.data.data.forEach(e => {
            let o = { "value": '', "address": '', "estateId": '' };
            o["value"] = e.estateName;
            o["address"] = e.address;
            o["estateId"] = e.estateId;
            // arr.push(o);
            this.estateList.push(o);
          });
          // console.log('arr==>', arr)
          console.log('this.estateList==>', this.estateList)
        }
      }).catch(err => {
        console.log('err==>', err)

      })
      // return arr;
    },
    // 保存小区id
    handleSelect(item) {
      console.log(item);
      this.editData.estateId = item.estateId;
    },
    // 验证小区名
    validEstate(rule, value, callback) {
      if (!value) {
        callback(Error("请输入小区名或楼盘"))
      } else {
        callback();
      }
    },
    // 验证价格
    validSup(rule, value, callback) {
      if (!value) {
        callback(Error("请输入价格"));
      } else {
        callback()
      }
    },
    // 验证建筑面积
    validBuiltArea(rule, value, callback) {
      if (!value) {
        callback(Error("请输入建筑面积"));
      } else {
        callback();
      }
    },
    // 验证姓名
    validUsername(rule, value, callback) {
      if (!value) {
        callback(Error("请输入姓名"));
      } else {
        callback();
      }
    },
    // 验证手机号
    validPhone(rule, value, callback) {
      if (value === "") {
        callback(new Error("请输入手机号"));
      } else if (!/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(value)) {
        callback(new Error("手机格式错误!"));
      } else {
        callback();
      }
    },
    // 编辑信息
    openEdit(o) {
      let houseNumber = o.houseNum.split(/[栋房]/);
      let houseKind = o.kind.split(/[室厅卫]/);
      this.editData = {
        id: o.id,
        estate: o['estate.estateName'],
        estateId: o.estateId,
        dgName: houseNumber[0],
        number: houseNumber[1],
        kind1: houseKind[0] + '室',
        kind2: houseKind[1] + '厅',
        kind3: houseKind[2] + '卫',
        sup: o.sup,
        builtArea: o.builtArea,
        userName: o.userName.split('先生')[0],
        sex: o.userName.slice(-2) == '先生' ? 1 : 0,
        userPhone: o.userPhone,
      }
      this.loadAll();
      this.dialog.edit = true;
    },
    // 当前页
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.params.page = val;
      this.init();
    },
    // 发起委托
    selling() {
      this.$refs['editData'].validate((valid) => {
        if (valid) {
          if (!this.editData.estateId) {
            this.$message.warning("请输入有效的小区名或楼盘")
            return
          }
          if (!this.editData.dgName || !this.editData.number) {
            this.$message.warning("请填写完整栋阁房号");
            return
          }
          if (!this.editData.kind1 || !this.editData.kind2 || !this.editData.kind3) {
            this.$message.warning("请填写完整户型");
            return
          }
          let data = {
            id: this.editData.id,
            estateId: this.editData.estateId,
            houseNum: this.editData.dgName + '栋' + this.editData.number + '房',
            kind: this.editData.kind1 + this.editData.kind2 + this.editData.kind3,
            sup: Number(this.editData.sup),
            builtArea: Number(this.editData.builtArea),
            sub: Math.round((Number(this.editData.sup)) / (Number(this.editData.builtArea)) * 10000),
            userName: this.editData.userName + (this.editData.sex == 1 ? '先生' : '女士'),
            userPhone: this.editData.userPhone,
            state: 0,
            kind1: parseInt(this.editData.kind1),
            kind2: parseInt(this.editData.kind2),
            kind3: parseInt(this.editData.kind3),
          }
          this.axios({
            method: 'post',
            url: this.baseUrl + '/editHouse',
            data: data
          }).then(res => {
            console.log('res==>', res)
            if (res.data.code == 200) {
              this.$message.success('发起委托成功')
              this.dialog.edit = false;
              this.init();
            } else {
              this.$message.error('请重新申请委托')
            }
          }).catch(err => {
            console.log('err==>', err)
            this.$message.error(res.data.msg)
          })
        }
      })
    },
    // 取消委托
    cancelSell(o) {
      this.axios({
        method: 'put',
        url: this.baseUrl + '/editHouse',
        params: {
          id: o.id,
          state: 3,
        }
      }).then(res => {
        console.log('res==>', res)
        if (res.data.code == 200) {
          this.$message.success('取消委托成功')
          this.init();
        } else {
          this.$message.error('取消委托失败')
        }
      }).catch(err => {
        console.log('err==>', err)
        this.$message.error(res.data.msg)
      })
    },
    // 删除记录
    delRecord(o) {
      this.axios({
        method: 'delete',
        url: this.baseUrl + '/deleteHouse',
        params: {
          id: o.id,
        }
      }).then(res => {
        console.log('res==>', res)
        if (res.data.code == 200) {
          this.$message.success('删除记录成功')
          this.init();
        } else {
          this.$message.error('删除记录失败')
        }
      }).catch(err => {
        console.log('err==>', err)
        this.$message.error(res.data.msg)
      })
    },

  },
}
</script>

<style lang="less" scoped>
@theme: #00b16a;
.sellingRecord {
  .title {
    font-size: 20px;
    font-weight: bold;
    color: #000;
    margin-bottom: 20px;
  }
  .el-pagination {
    margin-top: 30px;
    text-align: center;
  }
  .btns {
    .el-button {
      margin-left: 0px;
      margin-right: 10px;
    }
  }

  /deep/ .el-dialog {
    border-radius: 6px;
    b {
      font-size: 20px;
    }
    .inline-input {
      width: 370px;
    }
    .houseNumber {
      width: 175px;
      & + .houseNumber {
        margin-left: 20px;
      }
    }
    .kind {
      width: 110px;
      & + .kind {
        margin-left: 20px;
      }
    }
    .user-name {
      .el-input {
        width: 260px;
      }
      .sex {
        display: flex;

        > a {
          height: 38px;
          flex: 1;
          width: 50px;
          border: 1px solid #dcdfe6;
          text-align: center;
          line-height: 38px;
          color: #ccc;

          &.active {
            border-color: @theme;
            color: @theme;
          }
        }
      }
    }
  }
}
</style>